package edu.gatech.oad.OTConfig;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.JScrollPane;


public class WagonInventoryPanel extends JPanel {

	/**
	 * This panel holds the list of items the player has in their wagon('s inventory)
	 * 
	 * @author Amy Lambeth
	 * @version 2.0 10/19/2011
	 */
	
	private static final long serialVersionUID = 1L;
	DefaultListModel model;
	JList list;
	private InventoryController invControl=new InventoryController();
	private Inventory wagonInv=invControl.getWagonInventory();	//Get instance of Wagon Inventory
	
	/**
	 * Create the panel.
	 */
	public WagonInventoryPanel() {
		
		model = new DefaultListModel();
		
		//Create new InventoryController
		
		
		
		
		
		//Set up JList for Wagon Inventory
		list = new JList(model);
		list.setToolTipText("Wagon Inventory");
		list.setValueIsAdjusting(true);
		JScrollPane bar = new JScrollPane(list);
		bar.setMinimumSize(new Dimension(300,100));
		add(bar);
		
		for (Item item:wagonInv){
			model.addElement(item.getName()+"\t Quantity:"+item.getQuantity()+
					"\t Weight:"+item.getWEIGHT_INDIVIDUAL()+"\t Price:"+item.getPRICE());
		}
				
		MouseListener listener = new MouseAdapter(){
			int answer;
			int delimiter;
			public void mouseClicked(MouseEvent e){
				if(e.getClickCount()==2){
					boolean valid = false;
					while(!valid)
					try{

						 answer = Integer.parseInt(JOptionPane.showInputDialog("How much of " + ((String)model.getElementAt(list.getSelectedIndex())).trim() + " would you like to sell"));
						valid = true;
					}
					catch(Exception exception){
					}
					
					String current = (String) model.getElementAt(list.getSelectedIndex());
					//Repopulate item if number to sell is changed to zero.
					if (answer==0){
						for (Item item:wagonInv){
							model.addElement(item.getName()+"\t Quantity:"+item.getQuantity()+
									"\t Weight:"+item.getWEIGHT_INDIVIDUAL()+"\t Price:"+item.getPRICE());
						}
					}
					else{
					delimiter = current.indexOf("Quantity:");
					current = current.substring(0, delimiter) + "Selling: " + answer;
					model.setElementAt(current, list.getSelectedIndex());
					System.out.println("done");
					}
				}

			}
		};
		list.addMouseListener(listener);
	}

}
